package com.gopay.common.util;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Request工具类
 * 
 * @RequestUtils.java
 * @author yaobo
 * @2012-12-26 上午09:38:31 www.gopay.com.cn Inc.All rights reserved.
 */
public class RequestUtils {

    private static Logger logger = LoggerFactory.getLogger(RequestUtils.class);
    /**
     * 获取客户端真实IP地址
     * 
     * @param request
     * @return
     */
    public static String getRemoteRealIpAddr(HttpServletRequest request) {
        //************增加日志和235特殊处理，修改前请先联系我  edit by fanghw 20170804
        logger.info(String.format("原始请求源IP：x-forwarded-for=%s，Proxy-Client-IP=%s"
                        + "，WL-Proxy-Client-IP=%s，X-Real-IP=%s"
                        + "，RemoteAddr=%s",
                request.getHeader("x-forwarded-for"),request.getHeader("Proxy-Client-IP")
                ,request.getHeader("WL-Proxy-Client-IP"),request.getHeader("X-Real-IP")
                ,request.getRemoteAddr()));

        String type="X-Real-IP";
        String ip = request.getHeader("X-Real-IP");

        if(isBlank(ip)) {
            ip = request.getHeader("x-forwarded-for");
            type="x-forwarded-for";
        }

        if (isBlank(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            type="Proxy-Client-IP";
        }

        if (isBlank(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            type="WL-Proxy-Client-IP";
        }

        if (isBlank(ip)) {
            ip = request.getRemoteAddr();
            type="RemoteAddr";
        }

        // 当通过代理访问时，x-forwarded-for获取的IP地址格式：clientIP, proxy1IP, proxy2IP, ……
        // 添加过滤处理，只获取客户真实IP，过滤掉代理服务器IP
        ip=ip == null?"":ip.trim();
        if(ip.contains(",")) {
            String ips[] = ip.split(",");
            for (int i = 0; i < ips.length; i++) {
                String realIP = ips[i] == null ? "" : ips[i].trim();
                if (!"unknown".equals(realIP) && !"".equals(realIP)) {
                    ip = realIP;
                    break;
                }
            }
        }

        ip=ip == null?"":ip.trim();

        logger.info(String.format("[new]处理后的请求源IP=%s，类型=%s",ip,type));

        return ip;
    }

    private static boolean isBlank(String ip){
        return ip == null || ip.length()<4 || "unknown".equalsIgnoreCase(ip);
    }

}